import re

import requests
from lxml import etree
from pymongo import MongoClient

from 成都租房.chaojiyong import Chaojiying_Client


#  url(//static8.ziroom.com/phoenix/pc/images/price/new-list/1.png);background-position: -85.6px


class R():

    def __init__(self):
        self.headers = headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
        }
        self.client = MongoClient("127.0.0.1", 27017)

        # 数据库名字和集合名字，没有会自动创建
        self.collection = self.client["exam"]["data"]

    def main(self):
        for p in range(1, 6):
            self.isget = True
            url = "http://cd.ziroom.com/z/p%s/" % p

            response = requests.get(url=url, headers=self.headers)

            xhtml = etree.HTML(response.content.decode())

            xpath_head = xhtml.xpath('//div[@class="info-box"]')

            for x in xpath_head:
                title = x.xpath('./h5/a/text()')[0].strip()

                loucen = x.xpath('.//div[@class="desc"]/div[1]/text()')[0].strip()

                desc = x.xpath('.//div[@class="desc"]/div[2]/text()')[0].strip()

                # 获取字体图片地址
                price_info = x.xpath('./div[2]/span/@style')

                price = self.get_price(price_info)

                print("------------0", price)

                self.save(title, loucen, desc, price)

    def get_price(self, info):
        # 字体图片地址
        img_addr = re.findall(r"\((.*?)\)", info[0])[0]
        if self.isget:
            self.get_ret(img_addr)
            self.isget = False

        # 存放价格数字 差值的列表
        ret_list = []
        for i in info:
            index = re.findall(r'position: -(.*?)px', i)[0]
            ret_list.append(index)

        price = ""

        for i in ret_list:
            print(i)
            price += self.retstr[int(float(i) / 21.4)]

        print("价格为", price)
        return price

    def get_ret(self, img_addr):
        response = requests.get(url="http:" + img_addr, headers=self.headers)

        chaojiying = Chaojiying_Client('weitezhu', 'zhuweiwei666', '96001')  # 用户中心>>软件ID 生成一个替换 96001
        # im = open('rj.png', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
        ret = chaojiying.PostPic(response.content, 1010)
        print("超级鹰")
        print(ret)

        self.retstr = ret.get("pic_str")
        return ret.get("pic_str")

    def save(self, title, loucen, desc, price):

        a, title = title.split("·")

        title, dir = title.split("-")

        type = title[-3:-1]

        floor, all_foor = loucen.split(" | ")[1].split("/")

        self.collection.insert({
            "title": title,
            "type": type,
            "direction": dir,
            "floor": floor,
            "all_floor": all_foor,
            "position": desc,
            "price": price
        })

    def __del__(self):

        self.client.close()


if __name__ == '__main__':
    r = R()

    r.main()
